﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SqlAutoRun
{
    public class OSQLHepler
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dataSource">服务器名称</param>
        /// <param name="dataBaseName">数据库名</param>
        /// <param name="user">登录名</param>
        /// <param name="pwd">密码</param>
        public OSQLHepler(string dataSource, string dataBaseName, string user, string pwd)
        {
            DataSource = dataSource;
            DataBaseName = dataBaseName;
            User = user;
            Pwd = pwd;
        }
        /// <summary>
        /// 服务器名称
        /// </summary>
        public string DataSource { get; set; }
        /// <summary>
        /// 数据库名
        /// </summary>
        public string DataBaseName { get; set; }
        /// <summary>
        /// 登录名
        /// </summary>
        public string User { get; set; }
        /// <summary>
        /// 密码
        /// </summary>
        public string Pwd { get; set; }


        /// <summary>
        /// 利用osql实现执行sql脚本文件
        /// </summary>
        /// <param name="DirFile">sql文件路径</param>
        public void ExcutesqlFile(string DirFile)
        {
            System.Diagnostics.Process sqlProcess = new System.Diagnostics.Process();
            sqlProcess.StartInfo.FileName = "osql.exe ";
            //-S "127.0.0.1" - U "user" - P "pwd" - d "database" - i "D:\"
            sqlProcess.StartInfo.Arguments = $@" -S ""{DataSource}"" -U ""{User}"" -P ""{Pwd}""  -d ""{DataBaseName}"" -i ""{DirFile}"" ";
            sqlProcess.StartInfo.UseShellExecute = false;
            sqlProcess.StartInfo.RedirectStandardOutput = true;  //重定向输出
            sqlProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            sqlProcess.Start();
            System.IO.StreamReader sr = sqlProcess.StandardOutput;
            Console.WriteLine(sr.ReadToEnd());
            sqlProcess.WaitForExit();//程序安装过程中执行
            sqlProcess.Close();
        }
    }
}
